package com.yeskery.nut.scan.bean;

import com.yeskery.nut.annotation.environment.ConfigurationProperties;
import com.yeskery.nut.bean.BeanAlreadyRegisterException;
import com.yeskery.nut.bean.FactoryBeanRegister;
import com.yeskery.nut.core.Environment;
import com.yeskery.nut.scan.AnnotationHandler;
import com.yeskery.nut.scan.BeanAnnotationScanMetadata;
import com.yeskery.nut.scan.BeanCreator;
import com.yeskery.nut.util.ReflectUtils;

import java.util.Collection;

/**
 * 基于注解的ConfigurationProperties扫描器
 * @author sprout
 * @version 1.0
 * 2022-07-12 10:36
 */
public class AnnotationConfigurationPropertiesHandler implements AnnotationHandler {

    /** bean创建器 */
    private final BeanCreator beanCreator;

    /**
     * 构建基于注解的ConfigurationProperties扫描器
     * @param factoryBeanRegister FactoryBean注解器
     * @param environment 环境对象
     */
    public AnnotationConfigurationPropertiesHandler(FactoryBeanRegister factoryBeanRegister, Environment environment) {
        beanCreator = new ConfigurationPropertiesBeanCreator(factoryBeanRegister, environment);
    }

    @Override
    public void handle(Collection<Class<?>> beanClassCollection, Collection<BeanAnnotationScanMetadata> beanMetadataCollection) {
        for (Class<?> clazz : beanClassCollection) {
            BeanAnnotationScanMetadata beanAnnotationScanMetadata = new BeanAnnotationScanMetadata(ReflectUtils.getDefaultBeanName(clazz),
                    clazz, BeanAnnotationScanMetadata.Source.CONFIGURATION_PROPERTIES, false,
                    ConfigurationProperties.class, null);
            try {
                beanCreator.createBean(beanAnnotationScanMetadata);
            } catch (BeanAlreadyRegisterException e) {
                // Bean Already Register
            }
        }
    }
}
